package com.bd.wechat.service.impl;

import cn.hutool.core.util.StrUtil;
import com.bd.wechat.config.MinioConfig;
import com.bd.wechat.service.FileService;
import com.bd.wechat.utils.FileUploadUtils;
import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class MinioFileServiceImpl implements FileService {

    @Autowired
    private MinioConfig minioConfig;

    @Autowired
    private MinioClient client;

    @Override
    public String uploadFile(MultipartFile file) throws Exception {
        String fileName = FileUploadUtils.extractFilename(file);
        PutObjectArgs args = PutObjectArgs.builder()
                .bucket(minioConfig.getBucketName())
                .object(fileName)
                .stream(file.getInputStream(), file.getSize(), -1)
                .contentType(file.getContentType())
                .build();

        client.putObject(args);


        return minioConfig.getDownloadUrl() + "?bucketName=" + minioConfig.getBucketName() + "&objectName=" + "/" + fileName;
    }

    @Override
    public Boolean remove(String fileUrl) {
        return null;
    }

    @Override
    public byte[] download(String bucketName, String objectName, HttpServletResponse response) throws Exception {
        byte[] buffer = new byte[1024];
        int bytesRead;
        InputStream inputStream = null;
        try {
            inputStream = client.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).build());

            String downloadName = StrUtil.subAfter(objectName, "/", true);
            // 设置响应头
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setHeader("Content-Disposition", "attachment; filename=\"" + downloadName + "\"");
            // 获取响应的输出流
            OutputStream outputStream = response.getOutputStream();
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.flush();

        } catch (Exception e) {
            // 捕获并处理可能的IO异常
            e.printStackTrace();
        } finally {
            // 关闭输入流，释放资源
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return buffer;
    }
}
